package com.example.sekerim;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONObject;


import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class IntroPageActivity extends ActionBarActivity {

	private UserLoginTask mAuthTask = null;
	
	private TextView mWelcomeTextView;
	private TextView mRegistrationTextView;
	private EditText mEmailView;
	private EditText mPasswordView;
	private TextView mLoginErrorText;
	private Button mLoginButton;
	private Button mRegistrationButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro_page);

		String checkPref = SaveSharedPreference.getMailAddress(IntroPageActivity.this);
		if(checkPref.length() != 0){
			Intent startmain = new Intent(IntroPageActivity.this,HomePageActivity.class);
			startmain.putExtra("mailAddress", checkPref);
			startActivity(startmain);
			finish();
		}

		initializePageElements();
		
		mLoginButton.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});

		mRegistrationButton.setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent startmain = new Intent(IntroPageActivity.this,RegistrationActivityAccountInformation.class);
						startActivity(startmain);
					}
				});

	}

	public void initializePageElements()
	{
		mWelcomeTextView = (TextView) findViewById(R.id.login_welcome_text_field);
		mRegistrationTextView = (TextView) findViewById(R.id.login_registration_suggestion_text);
		mEmailView = (EditText) findViewById(R.id.login_username_field);
		mPasswordView = (EditText) findViewById(R.id.login_password_field);
		mLoginErrorText = (TextView) findViewById(R.id.login_error_text_field);
		mLoginButton = (Button) findViewById(R.id.login_button);
		mRegistrationButton = (Button) findViewById(R.id.login_registration_button);

		mWelcomeTextView.setText(Constants.login_welcome_text);
		mLoginButton.setText(Constants.login_button_text);
		mRegistrationTextView.setText(Constants.login_registration_text);
		mRegistrationButton.setText(Constants.login_registration_button_text);
		
		Typeface font = Typeface.createFromAsset(getAssets(), "fonts/beryliumbold.ttf");
		mWelcomeTextView.setTypeface(font);
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		String mEmail = mEmailView.getText().toString();
		String mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(Constants.login_empty_password_field_error);
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(Constants.login_empty_email_field_error);
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(Constants.login_incorrect_email_address);
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			mLoginErrorText.setText(Constants.login_process);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
			mLoginErrorText.setText("");
		}
	}
	
	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.

			String JSONString=null;
			try {
				/*
				URL local;
				local = new URL("GlobalStatic.DEPLOYMENT_URL+LogIn?isMobile=1&username=+mEmail+&password=+mPassword"); 
				BufferedReader in = new BufferedReader(new InputStreamReader(local.openStream()));		
				StringBuilder sb = new StringBuilder();

				String inputLine;
				while ((inputLine = in.readLine()) != null){
					//System.out.println(inputLine);
					sb.append(inputLine);
				}
				JSONString=sb.toString();
				in.close();

				JSONObject jObject = new JSONObject(JSONString);

				
				studentID =jObject.getString("studentID");
				if (!studentID.equals("-1")) {
					return true;
				}else{
					return false;
				}
				*/
				
				return false;
			}
			catch(Exception e){
				e.printStackTrace();

			}
			// TODO: register the new account here.
			return false;
		}

		/**
		 * Take related actions upon success or fail of a login attempt
		 */
		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;

			if (success) {
				
				//SaveSharedPreference.setMailAddress(IntroPageActivity.this, mEmailView.getText().toString());

				Intent startmain = new Intent(IntroPageActivity.this,HomePageActivity.class);
				startmain.putExtra("mailAddress", mEmailView.getText().toString());
				startActivity(startmain);
				finish();
			} else {
				mPasswordView
				.setError(Constants.login_invalid_login_attempt);
				mPasswordView.requestFocus();
			}
		}


		@Override
		protected void onCancelled() {
			mAuthTask = null;
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
}
